<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2016/2/17
 * Time: 16:29
 */

class TokenApp extends StorebaseApp {

    /**
     *获取token接口
     * @author lz
     * @date 2016-2-18
     */
    public function token(){
        $action = '获取token接口';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }
        //test_token_56c436c070ebf742774574
        $model = m('member');
        $token = $this->get_gp('token', 'P');
        $idfa = $this->get_gp('idfa', 'P');
        if(!$idfa){
            $this->ajax_return(FLAG_ERROR, "参数错误！");
        }
        $sql = "SELECT user_id FROM ".DB_PREFIX."member WHERE accessToken='".$token."'";
        $user = $model->getRow($sql);
        if($user) {
            $user_id = $user['user_id'];
            import('redis.lib');
            /**
             * 1、该接口给IOS客户端一个token
             * 2、只要IOS发来携带access_token的请求就要给IOS客户端返回一个新的token
             * 3、并且通过access_token获取到user_id 把新的token作为key获取的user_id作为value存储到Redis
             */
            //获取一个token
            $sign = $this->getToken(SIGN);
            $redis = new RedisDB(REDISHOST,REDISPWD);
            //存储Redis $token作为key $user_id作为value
            $value = $sign."-".$user_id;
            $result = $redis->setex($idfa,$value,7200);
            if($result) {
                $data = array('sign'=>$sign,'expires_in'=>7200);
                $this->ajax_return(FLAG_OK, '',$data);
            } else {
                $this->ajax_return(FLAG_ERROR, '获取token失败！');
            }
        } else {
            $this->ajax_return(FLAG_ERROR, '无效的access_token');
        }
    }


    /**
     * 1、首先判断Redis里面是否包含token数据
     * 2、如果包含获取相应的user_id信息
     * 3、如果不包含生成token返回并且存储到Redis。存储7200s
     */
} 